<?php
/**
 * Class descript.
 * User: chan
 * Date: 2017/9/2 12:20
 */

namespace app\wap\controller;

use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Text;
use think\Cache;
use think\Controller;
use think\Session;
use \app\api\logic\Member as MemberLogic;

class Wechat extends Controller
{
    public static $targetUrl = 'http://qch.gzldrj.com/qchwap/#/index?';
    protected static $app;
    function __construct()
    {
        Session::start();
        $options = [
            'debug'  => true,
            'app_id' => config('wx.app_id'),
            'secret' => config('wx.app_secret'),
            'token'  => config('wx.token'),

            'log' => [
                'level'      => 'debug',
                'permission' => 0777,
                'file'       => '/tmp/easywechat.log',
            ],

            // ...
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => 'http://qch.gzldrj.com/wap/wechat/oauthCallback',
            ],
            // ..
        ];

        // 使用配置来初始化一个项目。
        self::$app = new Application($options);
    }
	
	/**
	 * 获取实例配置
	 */
	public function getApp(){
		return self::$app;
	}
	

    function run()
    {
        $server = self::$app->server;
        $this->responseMsg($server);
        $server->serve()->send();
    }
    function responseMsg($server)
    {
        $server->setMessageHandler(function ($message) {
            switch ($message->MsgType) {
                case 'event':
                    return $this->receiveEvent($message);
                    break;
                case 'text':
                    //获取到用户发送的文本内容
                    $content = $message->Content;
                    //把内容发给用户
                    return new Text(['content' => $content]);
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }
            // ...
        });
    }

    public function menu()
    {
        $menu = self::$app->menu;
        $buttons = [
            [
                "type" => "view",
                "name" => "首页",
                "url"  => "http://qch.gzldrj.com/qchwap/#/index"
            ],
            [
                "type" => "view",
                "name" => "票务预订",
                "url"  => "http://qch.gzldrj.com/qchwap/#/reserve"
            ],
            [
                "name"       => "会员中心",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "会员中心",
                        "url"  => "http://qch.gzldrj.com/qchwap/#/center"
                    ],
                    [
                        "type" => "view",
                        "name" => "领券中心",
                        "url"  => "http://qch.gzldrj.com/qchwap/#/couponCenter"
                    ],
                    [
                        "type" => "view",
                        "name" => "领会员卡",
                        "url"  => "http://qch.gzldrj.com/qchwap/#/couponCenter"
                    ],
                ],
            ]
        ];
        return $menu->add($buttons);
    }

    public function access_token()
    {
        // 获取 access token 实例
        $accessToken = self::$app->access_token;
        $token = $accessToken->getToken(); // token 字符串
        return $token;
    }
    // 强制重新从微信服务器获取 token.
    public function forceRefresh()
    {
        // 获取 access token 实例
        $accessToken = self::$app->access_token;
        $token = $accessToken->getToken(true);
        return $token;
    }

    public function oauth()
    {
        $oauth = self::$app->oauth;
        return $oauth->redirect()->getTargetUrl();
    }
    public function oauthCallback()
    {
        $oauth = self::$app->oauth;
        // 获取 OAuth 授权结果用户信息
        $wxUser = $oauth->user();
        $wxResult = $wxUser->toArray();

        $user = (new MemberLogic($wxResult))->getUser($wxResult);
        $this->prepareCachedValue($wxResult, $user);

        $Oauth2 = new \app\api\service\Oauth2();
        $userTokenData = $Oauth2::generateToken($user);
        // 跳转前端页面，前端使用访问令牌更新用户令牌信息
        header('location:'. self::$targetUrl.'access_token='.$userTokenData['access_token'].'&refresh_token='.$userTokenData['refresh_token']);
    }

    /**
     * 缓存处理
     * @param $wxResult
     * @param $user
     * @return mixed
     */
    private function prepareCachedValue($wxResult, $user)
    {
        $user['original'] = $wxResult['original'];
        Cache::set($wxResult['original']['openid'], json_encode($user), config('secure.token_expire_in'));
        return $user;
    }

    /**
     * 接收用户事件，关注等
     * @param $message
     */
    private function receiveEvent($message)
    {
        switch ($message->Event)
        {
            case "subscribe":
                $contentStr = "欢迎关注我们";
                break;
            case "unsubscribe":
                $contentStr = "感谢你的使用，欢迎下次回来！";
                break;
            case "CLICK":
                break;
            case "LOCATION":
                $position['lat'] = $message->Latitude;
                $position['lng'] = $message->Longitude;
                session('position',$position);
                break;
            default:
			    $contentStr = "";
                break;
        }
        return $contentStr;
    }

}